<?php

namespace App\Http\Controllers;

use App\Http\Requests\ChapterRequest;
use App\Models\Chapter;
use App\Models\Repository;
use Illuminate\Http\Request;

class RepositoryForkController extends Controller
{
    public function index(Request $request, Repository $repository)
    {

        return view('resources.repository.fork.index')->with('forks', $repository->forks()->with('forks')->get());
    }

    public function create(Request $request, Repository $repository)
    {

//        $this->authorize('repositories.fork', $repository);
        $sequence = $repository->currentChapters()->max('sequence') + 1;
        return view('resources.repository.fork.create')->with(compact('repository', 'sequence'));
    }

    public function store(ChapterRequest $request, Repository $repository, Chapter $chapter)
    {

//        $this->authorize('repositories.fork', $repository);

        $forkRepository = $repository->replicate();
        $forkRepository->views = 0;
        $forkRepository->parent_id = $repository->id;
        $forkRepository->save();


        $repository->currentChapters->each(
            function (Chapter $chapter) use ($forkRepository) {
                $chapter->repositories()->attach($forkRepository->id, ['sequence' => $chapter->pivot->sequence, 'is_using' => $chapter->pivot->is_using]);
            }
        );

        //更新上传上来的那一章

        $chapter->fill($request->only(['title', 'content']));
        $chapter->save();


        $forkRepository->attachChapter($chapter, $request->sequence);

        return redirect()->route('repositories.show', ['id' => $forkRepository->id]);
    }
}
